package com.angel.core.base;

import java.util.Date;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;

import com.angel.core.util.Pager;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;

/**
 * @author cheng sir
 * 2016年9月5日上午17:47:54
 */
public abstract class BaseProviderImpl<T extends BaseModel> implements BaseProvider<T>{
	@Autowired
	BaseMapper<T> mapper;

	//分页查询
	public Pager findAll(T record,Pager pager){
//		Pager pager = new Pager();
//		if(currentPage == null) currentPage = 1;
//		if(pageSize == null) pageSize = 5;
//		PageHelper.startPage(currentPage, pageSize);
		PageHelper.startPage(pager.getCurrentPage(), pager.getPageSize());
		List<Map<String, Object>> list = mapper.findAll(record);
		PageInfo<Map<String, Object>> pageInfo = new PageInfo<Map<String, Object>>(list);
//		pager.setCurrentPage(currentPage);
//		pager.setPageSize(pageSize);
		pager.setTotal(pageInfo.getTotal());
		pager.setTotalPages(pageInfo.getPages());
		pager.setList(pageInfo.getList());
		return pager;
	}
	
	public Pager findAll(List<Map<String,Object>> list ,Pager pager){
		PageHelper.startPage(pager.getCurrentPage(), pager.getPageSize());
		PageInfo<Map<String, Object>> pageInfo = new PageInfo<Map<String, Object>>(list);
		pager.setTotal(pageInfo.getTotal());
		pager.setTotalPages(pageInfo.getPages());
		pager.setList(pageInfo.getList());
		return pager;
	}
	
	public List<Map<String, Object>> findAll(T record){
		return mapper.findAll(record);
	}
	
	public int insert(T record) {
		Date date = new Date();
		record.setCreateTime(date);
		record.setUpdateTime(date);
		record.setEnable(1);
		return mapper.insert(record);
	}

	public int updateById(T record) {
		Date date = new Date();
		record.setUpdateTime(date);
		return mapper.updateByPrimaryKeySelective(record);
	}
	
	public int delById(T record){
		Date date = new Date();
		record.setUpdateTime(date);
		record.setEnable(0);
		return mapper.updateByPrimaryKeySelective(record);
	}

	public T findById(T record){
		return mapper.selectByPrimaryKey(record.getId());
	}
	
	public int insertAll(List<T> list){
		Date date = new Date();
		for(int i = 0;i<list.size();i++){
			list.get(i).setCreateTime(date);
			list.get(i).setUpdateTime(date);
			list.get(i).setEnable(1);
		}
		return mapper.insertAll(list);
	}
	
}
